/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jack.utils;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 *
 * from http://gophinight.bokee.com/5422985.html 
 * http://dev.10086.cn/cmdn/wiki/index.php?doc-view-1981
 */
public class ImageUtils {
    /*图像变换
     用法举例:
     1.将一张图片pic转换成176*208的图
     pic=transImage(pic,176,208);
     2.将一张图片pic转换成原来的两倍大
     pic=scaleImage(pic,2,1);
     3.将一张图片pic转换成原来的三分之二
     pic=scaleImage(pic,2,3);     
     */

    /**
     *J2me图片缩放
     */ 
    
    /**
     *
     * @param src 需要变换的图片 图片变换比例 scales1:scales2
     * @param scales1 新图片
     * @param scales2 旧图片
     * @return
     */
    public static Image scaleImage(Image src, int scales1, int scales2) {
        return transImage(src, src.getWidth() * scales1 / scales2, src
                .getHeight()
                * scales1 / scales2);
    }

    /**
     *
     * @param src 需要变换的图片
     * @param w 要变换的宽
     * @param h 要变化的高
     * @return
     */
    public static Image transImage(Image src, int w, int h) {
        int srcW = src.getWidth();// 图片的宽度   
        int srcH = src.getHeight();// 图片的高度   
        int dstW = w, dstH = h;
        Image tmp = Image.createImage(dstW, srcH); // 申请个宽为dstW高为srcH的图片空间   
        Graphics g = tmp.getGraphics();
        int scale = 16;
        int delta = (srcW << scale) / dstW;// 扫描长度   
        int pos = delta / 2;// 扫描位置   
        for (int x = 0; x < dstW; x++) {
            g.setClip(x, 0, 1, srcH);
            g.drawImage(src, x - (pos >> scale), 0, Graphics.LEFT
                    | Graphics.TOP);
            pos += delta;
        }
        Image dst = Image.createImage(dstW, dstH);
        g = dst.getGraphics();
        delta = (srcH << scale) / dstH;
        pos = delta / 2;
        for (int y = 0; y < dstH; y++) {
            g.setClip(0, y, dstW, 1);
            g.drawImage(tmp, 0, y - (pos >> scale), Graphics.LEFT
                    | Graphics.TOP);
            pos += delta;
        }
        tmp = null;
        return dst;
    }

}
